package com.rafahead.bloquinho;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.BackStackEntry;
import android.util.Log;

import com.rafahead.bloquinho.PlayerListFragment.PlayerSelectedCallBack;
import com.rafahead.bloquinho.dao.PlayerDAO;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener, MatchListFragment.MatchSelectedCallBack, PlayerSelectedCallBack{

	private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";



	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);


		// For each of the sections in the app, add a tab to the action bar.
		actionBar.addTab(actionBar.newTab().setText(R.string.title_section1).setTabListener(this));
		actionBar.addTab(actionBar.newTab().setText(R.string.title_section2).setTabListener(this));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP);

	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
			getActionBar().setSelectedNavigationItem(
					savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
				getActionBar().getSelectedNavigationIndex());
	}



	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		if (tab!=null){
			if (tab.getPosition()==0){

				// Check whether the activity is using the layout version with
				// the fragment_container FrameLayout. If so, we must add the first fragment
				if (findViewById(R.id.container) != null) {

					
					MatchListFragment fragment = new MatchListFragment();
					fragment.setArguments(getIntent().getExtras());

/*					boolean inBSEntry = false;
					int count = getSupportFragmentManager().getBackStackEntryCount();
					for (int i = count; count > 0; i--) {
						BackStackEntry stackEntry = getSupportFragmentManager().getBackStackEntryAt(i-1);
						if (stackEntry!=null && stackEntry.getName().compareTo(MatchListFragment.class.toString())==0){
							inBSEntry=true;
							break;
						}
					}*/
					
					android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

					// Replace whatever is in the fragment_container view with this fragment,
					// and add the transaction to the back stack so the user can navigate back
					transaction.replace(R.id.container, fragment);
					transaction.addToBackStack(MatchListFragment.class.toString());

					// Commit the transaction
					transaction.commit();
				}



			}else if (tab.getPosition()==1){
				// Check whether the activity is using the layout version with
				// the fragment_container FrameLayout. If so, we must add the first fragment
				if (findViewById(R.id.container) != null) {

					PlayerListFragment fragment = new PlayerListFragment();
					fragment.setArguments(getIntent().getExtras());

					android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

					// Replace whatever is in the fragment_container view with this fragment,
					// and add the transaction to the back stack so the user can navigate back
					transaction.replace(R.id.container, fragment);
					transaction.addToBackStack(PlayerListFragment.class.toString());

					// Commit the transaction
					transaction.commit();
				}

			}
		}
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}

	@Override
	public void onMatchSelected(int position) {

		// The user selected the headline of an article from the HeadlinesFragment

		// Capture the article fragment from the activity layout
		MatchDetailFragment matchFrag = (MatchDetailFragment)getSupportFragmentManager().findFragmentById(R.id.matchdetail_fragment);

		if (matchFrag != null) {
			// If article frag is available, we're in two-pane layout...

			// Call a method in the ArticleFragment to update its content
			matchFrag.updateMatchView(position);

		} else {
			// If the frag is not available, we're in the one-pane layout and must swap frags...

			// Create fragment and give it an argument for the selected article
			MatchDetailFragment newFragment = new MatchDetailFragment();
			Bundle args = new Bundle();
			args.putInt(MatchDetailFragment.ARG_POSITION, position);
			newFragment.setArguments(args);
			android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

			// Replace whatever is in the fragment_container view with this fragment,
			// and add the transaction to the back stack so the user can navigate back
			transaction.replace(R.id.container, newFragment);
			transaction.addToBackStack(MatchDetailFragment.class.toString());

			// Commit the transaction
			transaction.commit();
		}	

	}

	@Override
	public void onPlayerSelected(long id) {
		// Create fragment and give it an argument for the selected article
		PlayerEditFragment newFragment = new PlayerEditFragment();
		Bundle args = new Bundle();
		args.putLong(PlayerDAO.COLUMN_ID, id);
		newFragment.setArguments(args);
		android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

		// Replace whatever is in the fragment_container view with this fragment,
		// and add the transaction to the back stack so the user can navigate back
		transaction.replace(R.id.container, newFragment);
		transaction.addToBackStack(PlayerEditFragment.class.toString());

		// Commit the transaction
		transaction.commit();


	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		FragmentManager manager = getSupportFragmentManager();
		int count = manager.getBackStackEntryCount();
		if (count > 0) {
			
			int entry =count-1;
			if (entry >= 0){
				BackStackEntry backSEntry= manager.getBackStackEntryAt(entry);
				if (backSEntry!=null){
					Log.w(MainActivity.class.toString(), "entry name:" + backSEntry.getName());
					if (backSEntry.getName().compareTo(MatchListFragment.class.toString())==0){
						getActionBar().getTabAt(0).select();
					}else if (backSEntry.getName().compareTo(PlayerListFragment.class.toString())==0){
						getActionBar().getTabAt(1).select();
					}
				}
			}
			
			
		} else if (count ==0){
			super.onBackPressed();
			
		}	
			
	}

	/*	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.activity_main, menu);

        // Calling super after populating the menu is necessary here to ensure that the
        // action bar helpers have a chance to handle this event.

		return super.onCreateOptionsMenu(menu);
	}*/


}
